package utils

import (
	"database/sql"
	"flag"
	"fmt"
	_ "github.com/denisenkom/go-mssqldb"
	"log"
)

var debug = flag.Bool("debug", true, "enable debugging")
var password = flag.String("password", "admin", "the database password")
var port *int = flag.Int("port", 8888, "the database port")
var server = flag.String("server", "127.0.0.1", "the database server")
var user = flag.String("user", "sa", "the database user")
var database = flag.String("database", "master", "the database name")

func GetDB() (*sql.DB, error) {
	if *debug {
		fmt.Printf(" password:%s\n", *password)
		fmt.Printf(" port:%d\n", *port)
		fmt.Printf(" server:%s\n", *server)
		fmt.Printf(" user:%s\n", *user)
	}
	connString := fmt.Sprintf("server=%s;database=%s;user id=%s;password=%s;port=%d;encrypt=disable", *server, *database, *user, *password, *port)
	if *debug {
		fmt.Printf(" connString:%s\n", connString)
	}
	db, err := sql.Open("mssql", connString)
	if err != nil {
		log.Fatal("Open connection failed:", err.Error())
		return nil, err
	}
	err = db.Ping()
	if err != nil {
		fmt.Print("PING:%s", err)
		return nil, err
	}
	return db, nil
}
